<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Post extends BackendController
{
	public $type = array();

	function __construct()
	{
		parent::__construct();
		$this->type = array(
			0=>lang('post'),
			1=>lang('image'),
			2=>lang('video'),
		);
		$this->lang->load('post');
		$this->load->model('post_model');
		$this->load->model('user_model');
		$this->load->model('category_model');
	}
	public function index($page=0)
	{
		$page = intval(str_replace('page-', '', $page));
		$limit = $this->config->item('per_page');
		if($page < 1) $page = 1;
		$limit_start = ($page - 1) * $limit;

		$where = array();

		$keyword = $this->filter->get('keyword');
		if($keyword)
		{
			$where_like = $this->db->escape('%'.$this->db->escape_like_str($keyword).'%');
			$where[] = 'title LIKE '.$where_like;
		}

		$category_id = $this->filter->get('category_id');
		$category = $this->category_model->get($category_id);
		if($category)
		{
			$cat_ids = array($category->id);
			$where[] = 'category_id IN ( '.implode(', ', $cat_ids).' ) ';
		}

		$user_id = $this->filter->get('user_id');
		if($user_id)
		{
			$where[] = 'created_by = '.$user_id;
		}

		if($where)
		{
			$this->post_model->list_where = implode(' AND ', $where);
		}

		$this->post_model->list_ordering = $this->filter->get('ordering', 'id');
		$this->post_model->list_direction = $this->filter->get('direction', 'DESC');
		$items = $this->post_model->getList($limit, $limit_start);
		foreach($items as $idx=>$item)
		{
			$items[$idx]->creator = $this->user_model->getItem($item->created_by);
			$items[$idx]->category = $this->category_model->getItem($item->category_id);
		}
		$total = $this->post_model->getTotal();

		$this->load->library('pagination');
		$link = site_url('admin/post/index');
		$this->pagination->initialize( array(
			'base_url' => $link,
			'first_url' => $link,
			'total_rows' => $total,
			'per_page' => $limit,
			'prefix' => 'page-',
			'cur_page' => $page,
		) );
		$rows = $this->category_model->getRoot();
		$categories = array(''=>lang('select_category'));
		foreach($rows as $row)
		{
			$categories[$row->id] = $row->title;
			if($row->child)
			{
				foreach($row->child as $child_id)
				{
					$child = $this->category_model->getItem($child_id);
					$categories[$child->id] = '&ndash; '.$child->title;
				}
			}
		}
		$rows = $this->user_model->getList();
		$users = array(''=>lang('select_user'));
		foreach($rows as $row)
		{
			$users[$row->id] = $row->fullname;
		}
		$data = array(
			'link'=>$link,
			'items'=>$items,
			'filter'=>$this->filter->getdata(),
			'ordering'=>$this->post_model->list_ordering,
			'direction'=>$this->post_model->list_direction,
			'type'=>$this->type,
			'users'=>$users,
			'categories'=>$categories,
			'category_id'=>$category_id,
			'user_id'=>$user_id,
		);

		$this->filter->store();
		if($this->input->get('ajax'))
		{
			$temp = 'items_list';
		}
		else
		{
			$this->output->set_template('backend');
			$this->output->set_title(lang('post_manager'));
			$temp = 'items';
		}
		$this->load->view('backend/post/'.$temp, $data);
	}
	public function form($id=0)
	{
		$id = intval($id);
		$base_url_image = base_url().trim($this->config->item('folder_image'), '/').'/';
		if($id)
		{
			$item = $this->post_model->getItem($id);
			if(!$item)
			{
				$this->messages->add(lang('not_found'), 'e');
				redirect(site_url('admin/post/index'));
			}

			$item->content = preg_replace("/\<img([^\>\r\n]*?)src=([\'\"])/", '<img$1src=$2'.$base_url_image, $item->content);
			$this->output->set_title(lang('post_edit'));
		}
		else
		{
			$item = $this->post_model->blankItem();
			$item->published = 1;
			$this->output->set_title(lang('post_add'));
		}

		$this->load->library('form_validation');
		$this->form_validation->set_rules('title', 'lang:title', 'trim|required|min_length[3]|xss_clean');
		$this->form_validation->set_rules('published', 'lang:published', 'is_natural');
		$this->form_validation->set_rules('category_id', 'lang:category', 'required|is_natural');
		$this->form_validation->set_rules('image');
		$this->form_validation->set_rules('description|xss_clean');
		$this->form_validation->set_rules('content|xss_clean');
		$this->form_validation->set_rules('tag|xss_clean');

		if ($this->form_validation->run() == TRUE)
		{
			$data = $this->input->post();
			$data['alias'] = urlTitle($data['title']);
			if($data['tag'])
			{
				$tags = preg_split('/\s*,\s*/',trim($data['tag']),-1,PREG_SPLIT_NO_EMPTY);
				$data['tag'] = implode(',', $tags);
			}
			if($data['id'])
			{
				$data['modified_by'] = $this->user->id;
				$data['modified_time'] = mdate(lang('date_format_sql'), time());
			}
			else
			{
				$data['created_by'] = $this->user->id;
				$data['created_time'] = mdate(lang('date_format_sql'), time());
			}

			$data['content'] = str_replace($base_url_image, '', $data['content']);

			//upload image
			$file = $_FILES;
			$img = $_FILES['image'];
			if($img['error'] == 0)
			{
				$this->load->library('upload');

				$add_path = date('Y'). '/' .date('m');
				$upload_path = FCPATH. DIRECTORY_SEPARATOR .trim($this->config->item('folder_image'), '/');
				$upload_path .= DIRECTORY_SEPARATOR .$add_path;
				$upload_path = path_clean($upload_path);
				folder_create($upload_path);

				$oldimg = path_clean(FCPATH. DIRECTORY_SEPARATOR .trim($this->config->item('folder_image'), '/'). DIRECTORY_SEPARATOR .$item->image);
				file_delete($oldimg);

				$ext = $this->upload->get_extension($img['name']);
				$fname = basename($img['name'], $ext);
				$fname = time().'_'.urlTitle($fname).strtolower($ext);
				$config = array(
					'upload_path' => $upload_path,
					'file_name' => $fname,
					'allowed_types' => $this->config->item('allowed_types'),
					'max_size' => $this->config->item('max_filesize'),
					'max_width' => $this->config->item('max_image_width'),
					'max_height' => $this->config->item('max_image_height')
				);
				$this->upload->initialize($config);
				if($this->upload->do_upload('image'))
				{
					$img = $this->upload->data();
					$data['image'] = $add_path. '/'. $img['file_name'];
				}
				else
				{
					$this->messages->add($upload->display_errors(), 'e');
				}
			}

			$msg = $this->post_model->save($data);
			if($id)
				$this->messages->add(lang('update_successfully'));
			else
				$this->messages->add(lang('add_successfully'));

			redirect(site_url('admin/post/index'));
		}
		else
		{
			$this->messages->add(validation_errors(), 'e');
		}

		$rows = $this->category_model->getRoot();
		$categories = array(''=>lang('select_option'));
		foreach($rows as $row)
		{
			$categories[$row->id] = $row->title;
			if($row->child)
			{
				foreach($row->child as $child_id)
				{
					$child = $this->category_model->getItem($child_id);
					$categories[$child->id] = '&ndash; '.$child->title;
				}
			}
		}

		$this->output->set_template('backend');
		// ckeditor
		$timestamp = 'c9T85uF';
		$data = array(
			'item'=>$item,
			'categories'=>$categories,
			'timestamp'=>$timestamp,
			'type'=>$this->type,
		);
		$this->load->js(base_url().'assets/ckeditor/ckeditor.js?t='.$timestamp);
		$this->load->js(base_url().'assets/ckeditor/config.js?t='.$timestamp);
		$this->load->view('backend/post/form', $data);
	}
	public function toggle($field='', $id=0, $val=1)
	{
		$id = intval($id);
		$post = $this->post_model->getItem($id);

		if(in_array($field, array('published', 'approved', 'hot', 'subject_hot', 'ads')))
		{
			$data['id'] = $id;
			$data[$field] = intval($val);
			$this->post_model->update($data);
			$this->messages->add(lang('change_successfully'));
		}

		redirect(site_url('admin/post/index'));
	}
	public function delete($id=null)
	{
		$id = intval($id);
		if($this->post_model->delete($id))
		{
			$this->messages->add(lang('delete_successfully'));
		}
		else
		{
			$this->messages->add(lang('delete_unsuccessfully'));
		}
		redirect(site_url('admin/post/index'));
	}

}
